package com.hogae.system.service.impl;

import com.hogae.capital.domain.CapUserWallet;
import com.hogae.capital.mapper.CapUserWalletMapper;
import com.hogae.core.constant.UserConstants;
import com.hogae.core.core.domain.TreeSelect;
import com.hogae.core.core.domain.entity.SysRole;
import com.hogae.core.core.domain.entity.SysUser;
import com.hogae.core.exception.CustomException;
import com.hogae.core.utils.DateUtils;
import com.hogae.core.utils.SecurityUtils;
import com.hogae.core.utils.StringUtils;
import com.hogae.system.domain.SysUserRole;
import com.hogae.system.domain.SysUserTree;
import com.hogae.system.mapper.SysRoleMapper;
import com.hogae.system.mapper.SysUserMapper;
import com.hogae.system.mapper.SysUserRoleMapper;
import com.hogae.system.mapper.SysUserTreeMapper;
import com.hogae.system.service.ISysConfigService;
import com.hogae.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author hogae
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserTreeMapper userTreeMapper;

    @Autowired
    CapUserWalletMapper userWalletMapper;

    @Autowired
    SysUserTreeMapper sysUserTreeMapper;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserList(SysUser user,Long userId) {
        if(null != user.getParentUserId())userId = user.getParentUserId();
        SysUserTree userTree = userTreeMapper.selectSysUserTreeByUserId(userId);
        return userMapper.selectUserList(user,userTree.getUserIdLevel());
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过手机号查询用户
     *
     * @param phonenumber 手机号
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByPhonenumber(String phonenumber) {
        return userMapper.selectUserByPhonenumber(phonenumber);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户关系
        insertUserTree(user);
        // 新增用户与角色管理
        insertUserRole(user);
        //新增用户钱包
        insertUserWallet(user);
        return rows;
    }


    void insertUserWallet(SysUser user){
        CapUserWallet wallet = new CapUserWallet();
        wallet.setUserId(user.getUserId());
        wallet.setAmount(BigDecimal.ZERO);
        wallet.setCommissionsAmount(BigDecimal.ZERO);
        wallet.setFreezeCommissionsAmount(BigDecimal.ZERO);
        wallet.setStatus("1");
        wallet.setCreateTime(DateUtils.getNowDate());
        wallet.setProfitAmount(BigDecimal.ZERO);
        wallet.setFreezeProfitAmount(BigDecimal.ZERO);
        userWalletMapper.insertCapUserWallet(wallet);
    }
    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户关系
     *
     * @param user 用户对象
     */
    public void insertUserTree(SysUser user) {
        Long userId = user.getUserId();
        if (StringUtils.isNotNull(userId)) {
            Long parentUserId = user.getParentUserId();
            if (StringUtils.isNotNull(userId)) {
                SysUserTree parentUserTree = userTreeMapper.selectSysUserTreeByUserId(parentUserId);
                SysUserTree sysUserTree = new SysUserTree();
                sysUserTree.setParentUserId(parentUserId);
                sysUserTree.setUserId(userId);
                sysUserTree.setLevel(parentUserTree.getLevel()+1);
                sysUserTree.setUserName(user.getUserName());
                sysUserTree.setParentUserName(parentUserTree.getUserName());
                sysUserTree.setUserIdLevel(parentUserTree.getUserIdLevel()+user.getUserId()+'~');
                sysUserTree.setCreateTime(new Date());
                userTreeMapper.insertSysUserTree(sysUserTree);
            }else {
                throw new CustomException("必须指定上级用户");
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        //删除用户树关联关系
//        userMapper.deleteUserTreesByIds(userIds);
        //删除用户
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 查询用户树管理数据
     *
     * @param userTree 用户树信息
     * @return 用户树信息集合
     */
    @Override
    public List<SysUserTree> selectUserTreeList(SysUserTree userTree) {
        return userTreeMapper.selectSysUserTreeList(userTree);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param userTrees 用户树列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildUserTreeSelect(List<SysUserTree> userTrees) {
        List<SysUserTree> deptTrees = buildDeptTree(userTrees);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 获取该用户下级Id
     * @param userId
     * @return
     */
    @Override
    public List selectByParentUserId(Long userId) {
        return StringUtils.isNotNull(sysUserTreeMapper.selectByParentUserId(userId))?sysUserTreeMapper.selectByParentUserId(userId):null;
    }


    /**
     * 构建前端所需要树结构
     *
     * @param userTrees 用户树列表
     * @return 树结构列表
     */
    public List<SysUserTree> buildDeptTree(List<SysUserTree> userTrees) {
        List<SysUserTree> returnList = new ArrayList<SysUserTree>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysUserTree userTree : userTrees) {
            tempList.add(userTree.getUserId());
        }
        for (Iterator<SysUserTree> iterator = userTrees.iterator(); iterator.hasNext(); ) {
            SysUserTree userTree = (SysUserTree) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(userTree.getParentUserId())) {
                recursionFn(userTrees, userTree);
                returnList.add(userTree);
            }
        }
        if (returnList.isEmpty()) {
            returnList = userTrees;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysUserTree> list, SysUserTree t) {
        // 得到子节点列表
        List<SysUserTree> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysUserTree tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysUserTree> list, SysUserTree t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 得到子节点列表
     */
    private List<SysUserTree> getChildList(List<SysUserTree> list, SysUserTree t) {
        List<SysUserTree> tlist = new ArrayList<SysUserTree>();
        Iterator<SysUserTree> it = list.iterator();
        while (it.hasNext()) {
            SysUserTree n = (SysUserTree) it.next();
            if (StringUtils.isNotNull(n.getParentUserId()) && n.getParentUserId().longValue() == t.getUserId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }
}
